<template>
  <!-- 顶部导航 -->
  <div class="header">
    <div class="nav-links">
      <button @click="handleLogout" class="logout-btn">登出</button>
    </div>
  </div>

  <!-- 主体内容 -->
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <div class="system-title">管理系统</div>
      <ul class="menu">
        <li><router-link to="/manager" class="menu-link">首页</router-link></li>

        <li class="parent-menu" @click="toggleMenu('user')">
          <span class="menu-item">
            <span>用户管理</span>
            <span class="toggle-icon">{{ expanded.user ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.user" class="submenu">
            <li><router-link to="/userlist" class="submenu-link">用户列表</router-link></li>
            <li><router-link to="/adminlist" class="submenu-link">管理员列表</router-link></li>
          </ul>
        </li>

        <li class="parent-menu" @click="toggleMenu('product')">
          <span class="menu-item">
            <span>商品管理</span>
            <span class="toggle-icon">{{ expanded.product ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.product" class="submenu">
            <li><router-link to="/productlist" class="submenu-link">商品列表</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <div class="content-header">
        <div class="search-bar">
          <input type="text" placeholder="输入用户名或手机号查询" v-model="searchKeyword" @keyup.enter="handleSearch" />
          <button @click="handleSearch" class="btn btn-primary" style="margin-left: 10px;">查询</button>
        </div>
        <!-- 暂时隐藏新增按钮，因为注册通常由用户自己完成，管理员主要负责管理状态 -->
        <!-- <div class="btn-group">
          <button @click="showAddModal = true">增加</button>
        </div> -->
      </div>

      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>用户名</th>
            <th>手机号</th>
            <th>注册时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="loading">
          <tr>
            <td colspan="6" class="table-tip">正在加载，请稍候...</td>
          </tr>
        </tbody>
        <tbody v-else-if="errorMessage">
          <tr>
            <td colspan="6" class="table-tip error">{{ errorMessage }}</td>
          </tr>
        </tbody>
        <tbody v-else-if="users.length === 0">
          <tr>
            <td colspan="6" class="table-tip">暂无用户数据</td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr v-for="(item, index) in users" :key="item.userId">
            <td>{{ index + 1 }}</td>
            <td>{{ item.userName }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.registeredAt || '—' }}</td>
            <td>
              <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
            </td>
            <td>
              <button @click="openEditModal(item)" class="btn btn-sm btn-warning">修改状态</button>
              <button @click="openDeleteModal(item)" class="btn btn-sm btn-danger">删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 编辑用户弹窗 -->
      <div v-if="showEditModal" class="modal-overlay">
        <div class="modal-content">
          <h3>修改用户状态</h3>
          <div class="form-group">
            <label>用户名：</label>
            <input v-model="editingUser.userName" disabled />
          </div>
          <div class="form-group">
            <label>手机号：</label>
            <input v-model="editingUser.phone" disabled />
          </div>
          <div class="form-group">
            <label>状态：</label>
            <select v-model="editingUser.status">
              <option :value="1">正常</option>
              <option :value="0">禁用</option>
            </select>
          </div>
          <div class="modal-footer">
            <button @click="showEditModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmEdit" class="btn btn-primary">确认</button>
          </div>
        </div>
      </div>

      <!-- 删除确认弹窗 -->
      <div v-if="showDeleteModal" class="modal-overlay">
        <div class="modal-content">
          <h3>删除确认</h3>
          <p>确定要删除用户 "<strong>{{ itemToDelete?.userName }}</strong>" 吗？此操作不可恢复！</p>
          <div class="modal-footer">
            <button @click="showDeleteModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmDelete" class="btn btn-danger">确定删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const router = useRouter()
const users = ref([])
const searchKeyword = ref('')
const expanded = reactive({ user: true, product: false })
const loading = ref(false)
const errorMessage = ref('')
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const editingUser = ref(null)
const itemToDelete = ref(null)

const fetchUsers = async () => {
  loading.value = true
  errorMessage.value = ''
  try {
    const params = {}
    const keyword = searchKeyword.value.trim()
    if (keyword) {
      params.keyword = keyword
    }
    const res = await api.getUserList(params)
    users.value = Array.isArray(res.data) ? res.data : []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    errorMessage.value = error.message || '获取用户列表失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  fetchUsers()
}

const getStatusText = (status) => {
  return Number(status) === 1 ? '正常' : '禁用'
}

const getStatusClass = (status) => {
  return Number(status) === 1 ? 'text-success' : 'text-danger'
}

const toggleMenu = (key) => {
  expanded[key] = !expanded[key]
}

const openEditModal = (item) => {
  editingUser.value = { ...item }
  showEditModal.value = true
}

const confirmEdit = async () => {
  if (!editingUser.value) return
  try {
    await api.updateUserInfo(editingUser.value.userId, { status: editingUser.value.status })
    showEditModal.value = false
    await fetchUsers()
    alert('用户状态已更新')
  } catch (error) {
    console.error('更新用户状态失败:', error)
    alert(error.message || '更新用户状态失败，请稍后重试')
  }
}

const openDeleteModal = (item) => {
  itemToDelete.value = { ...item }
  showDeleteModal.value = true
}

const confirmDelete = async () => {
  if (!itemToDelete.value) return
  try {
    await api.deleteUser(itemToDelete.value.userId)
    showDeleteModal.value = false
    itemToDelete.value = null
    await fetchUsers()
    alert('用户已删除')
  } catch (error) {
    console.error('删除用户失败:', error)
    alert(error.message || '删除用户失败，请稍后重试')
  }
}

const handleLogout = () => {
  api.logout().finally(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/admin-login')
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
/* ========== 布局基础 ========== */
@import '@/CSS/ManagerPublicCss.css';
/* ========== 右侧内容 ========== */
@import '@/CSS/ManagerPageUserList.css';

.text-success {
  color: green;
  font-weight: bold;
}

.text-danger {
  color: red;
  font-weight: bold;
}

.table-tip {
  text-align: center;
  padding: 16px;
  color: #666;
}

.table-tip.error {
  color: #d93025;
}
</style>